package com.wonders.healthcitydoctor.ui.base;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.wonders.healthcitydoctor.R;
import com.wonders.healthcitydoctor.util.DateUtil;
import com.wonders.healthcitydoctor.util.LogUtil;
import com.wonders.healthcitydoctor.util.SPUtils;
import com.wonders.healthcitydoctor.util.SystemBarTintManager;

import java.util.Date;
import java.util.List;

import me.yokeyword.fragmentation.SwipeBackLayout;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import me.yokeyword.fragmentation_swipeback.SwipeBackActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by liyaqing on 2017/5/3.
 */

public class BaseBackActivity extends SwipeBackActivity implements  EasyPermissions.PermissionCallbacks,View.OnClickListener{
    private String TAG=this.getClass().getSimpleName();
    protected double curLatitude=0.0;//纬度
    protected double curLongitude=0.0;//经度
    protected String curCity="";

    private static final int RC_LOCATION_CONTACTS_PERM = 124;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;


    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackManager.getInstance().init(this) 来初始化滑动返回」
        // 在 super.onCreate(savedInstanceState) 之前调用该方法
//        initSwipeBackFinish();

        super.onCreate(savedInstanceState);
//        initSystemBar(true, R.color.colorPrimary);
        log(TAG + "------" + "onCreate");
//        getSwipeBackLayout().setEdgeOrientation(SwipeBackLayout.EDGE_LEFT); // EDGE_LEFT(默认),EDGE_ALL
    }

    @Override
    protected void onStart() {
        super.onStart();
        log(TAG + "------" + "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        log(TAG + "------" + "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        log(TAG + "------" + "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();

        log(TAG + "------" + "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        log(TAG + "------" + "onDestroy");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        log(TAG + "------" + "onRestart");
    }

    /**
     * 打印信息
     * @param msg
     */
    public void log(String msg){
        if (canLogMsg()){
            LogUtil.i(msg);
        }
    }

    /**
     * 控制activity的全局信息，是否能打印
     * @return
     */
    public boolean canLogMsg(){
        return true;
    }
    /**
     * 设置系统状态栏颜色
     * @param flag true启用系统状态栏颜色设置，false关闭
     * @param colorResourceId 颜色的id
     */
    public void initSystemBar(boolean flag, int colorResourceId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(flag);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(colorResourceId);
    }


    public void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }


    /**
     * 限制SwipeBack的条件,默认栈内Fragment数 <= 1时 , 优先滑动退出Activity , 而不是Fragment
     *
     * @return true: Activity可以滑动退出, 并且总是优先;  false: Activity不允许滑动退出
     */
    @Override
    public boolean swipeBackPriority() {
        return super.swipeBackPriority();
    }

    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }
    public boolean isRemoveCookie(){
        boolean isRemoveCookie=false;
        String currentTime= DateUtil.ConverToString(new Date());
        String preTime=(String) SPUtils.get(getApplicationContext(),getString(R.string.touchTime),"0000-00-00 00:00:00");
        long chaTime=DateUtil.timeCha(preTime,new Date());
        LogUtil.i("timecha",chaTime+","+preTime+","+currentTime);
        if (chaTime>=30){
            CookieSyncManager.createInstance(getApplicationContext());
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();//移除
            SPUtils.put(getApplicationContext(),getString(R.string.cookie),"");
            SPUtils.put(getApplicationContext(),getString(R.string.username),"");
            SPUtils.put(getApplicationContext(),"password","");
            SPUtils.put(getApplicationContext(),getString(R.string.isSavaPass),"");
            SPUtils.put(getApplicationContext(),getString(R.string.isAutoLogin),"");
            isRemoveCookie=true;
        }
        SPUtils.put(getApplicationContext(),getString(R.string.touchTime),currentTime);
        return isRemoveCookie;
    }

    @Override
    public void onClick(View view) {

    }

    public void getJwd() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
//        ref=new WeakReference<AMapLocationListener>(mLocationListener);
//        AMapLocationListener refAMapLocationListener=ref.get();
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        /**
         * 获取一次定位
         */
        //该方法默认为false，true表示只定位一次
        mLocationOption.setOnceLocation(false);
//        mLocationOption.setInterval(10000);
        mLocationClient.startLocation();
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            // TODO Auto-generated method stub
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    double locationType = amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    curLatitude = amapLocation.getLatitude();//获取纬度
                    curLongitude = amapLocation.getLongitude();//经度
                    curCity=amapLocation.getCity();
//                    setCurLatitude(curLatitude);
//                    setCurLongitude(curLongitude);

                    LogUtil.i(TAG+",Amap==经度：纬度", "locationType:" + locationType + ",curLatitude:" + curLatitude + ",curLongitude" + curLongitude);

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    LogUtil.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };




    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    public void locationAndContactsTask() {
        String[] perms = { Manifest.permission.ACCESS_FINE_LOCATION };
        if (EasyPermissions.hasPermissions(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Have permissions, do the thing!
            getJwd();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                    RC_LOCATION_CONTACTS_PERM, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        LogUtil.i(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
        getJwd();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        LogUtil.i(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}